#include "stdafx.h"
#include "ClientConsole.h"
#include "ZClientSocketNetworkController.h"
#include "ZRandomNumberGenerator.h"
#include "TestGameMessageHandler.h"

using	namespace	Z;

template<>	ClientConsole*	Singleton<ClientConsole>::msSingleton	= nullptr;

ClientConsole::ClientConsole()
:	mTransfering(false)
{
}

ClientConsole::~ClientConsole()
{
}

bool ClientConsole::handle(char command)
{
	if(!Win32Console::handle(command))
		return false;
	
	switch(command)	{
		case 't':
		case 'T':
			mTransfering	= !mTransfering;
			break;
	}
	return true;
}

bool ClientConsole::initialise()
{
	if(!Win32Console::initialise())
		return false;

	for(size_t i = 0; i < mClientSocket; ++i)	{
		mMessageManagers.push_back(MessageManagerPtr(new MessageManager(new ClientSocketNetworkController("10.255.141.11", 12345, 1), new TestGameMessageHandler)));
	}
	for(MessageManagers::iterator i = mMessageManagers.begin(); i != mMessageManagers.end(); ++i)	{
		bool result	= (*i)->start();
		assert(result);
	}
	return true;
}

void ClientConsole::finalise()
{
	Win32Console::finalise();

	for(MessageManagers::iterator i = mMessageManagers.begin(); i != mMessageManagers.end(); ++i)	{
		(*i)->cleanup();
	}
}

void ClientConsole::doProcess(float frameTime)
{
	static float accumTime	= 0.0f;
	const size_t kMaxDataSize	= 1024;
	const size_t kMinDataSize	= 1;
	static byte_t data[kMaxDataSize];
	const size_t dataSize	= Z::random((int)kMinDataSize, (int)kMaxDataSize);
	accumTime	+= frameTime;
	for(MessageManagers::iterator i = mMessageManagers.begin(); i != mMessageManagers.end(); ++i)	{
		(*i)->execute();
	}
	if(0.33f < accumTime)	{
		accumTime	-= 0.33f;
		if(mTransfering)	{
			for(MessageManagers::iterator i = mMessageManagers.begin(); i != mMessageManagers.end(); ++i)	{
				(*i)->send(data, dataSize, Z::ClientSocketNetworkController::host);
			}
		}
	}
}